﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using HRM.HRMServiceProxy;
using System.ServiceModel;
using System.IO;
using HRM.Utilities;


namespace HRM
{
    public partial class frmMergeBookList : DockContent
    {
        BranchClient wcfBranch;
        DepartmentClient wcfDepartment;       
        DoiSoClient wcfDoiSo;
        MainServiceClient wcfMain;
        EmployeeClient wcfEployee;
        int pageSize = 300;//UIParamater.pageSize;
        int currPage = 0;
        int itemCount = 0;
        int totalPage = 0;
        int doiso_ID = 0;
        int department_ID=0;
        int branch_ID = Program.intBranchID;
        int _month = DateTime.Now.Month;
        int _year = DateTime.Now.Year;
        string _selectedID = "";
        RoleRightInfo listRole;
        bool _loadedData = false;
        public frmMergeBookList()
        {
            InitializeComponent();
            LoadLanguage();
            wcfBranch = Service.Branch();
            wcfEployee = Service.Employee();
            wcfDepartment = Service.Department();
            wcfDoiSo = Service.DoiSo();
            wcfMain = Service.MainService();
            listRole = UIParamater.Quyen_DieuChinhSoBH;
            BuildVoucherGrid();
            if (!listRole.Update)
            {
                this.btnEdit.Image = Properties.Resources.app;
                this.btnEdit.Tag = "xem";
            }
            UISetting.LoadMonths(ref cboMonth);
            cboMonth.ComboBox.SelectedValue = Convert.ToUInt32(DateTime.Now.Month);
            UISetting.LoadYears(ref cboYear);           
            //UISetting.LoadTreeView3(ref tvBranch);    
            splitContainer1.Panel1Collapsed = true;            
            dgvList.ReadOnly = false;
            btnNew.Enabled = listRole.Create;
            btnEdit.Enabled = listRole.Update;
            btnDel.Enabled = listRole.Delete;            
            toolStripButton1.Enabled = listRole.Create;
            btnDoiso.Enabled = Program.isChuyenQuan;
            LoadData();
        }

        void LoadLanguage()
        {
            this.TabText = this.Text = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref btbprint);
        }

        private void BuildVoucherGrid()
        {
            dgvList.Columns.Clear();
            //Thêm cột Checkbox
            DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
            col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            col.Name = "Check";
            col.HeaderText = "Chọn";
            col.Width = 50;
            col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgvList.Columns.Add(col);
            col.Visible = true;

            UISetting.AddColumn(ref dgvList, "doiso_ID", "Mã chính", "", 1, false, true);
            UISetting.AddColumn(ref dgvList, "doiso_branchID", "Chi nhánh ID", "", 1, false, true);
            UISetting.AddColumn(ref dgvList, "doiso_employeeID", "Nhân viên ID", "", 1, false, true);
            UISetting.AddColumn(ref dgvList, "Employee_FullName", "Họ tên", "", 160, true, true);
            UISetting.AddColumn(ref dgvList, "Employee_DateOfBirth", "Ngày sinh", "", 100, true, true);
            UISetting.AddColumn(ref dgvList, "Employee_IDCardNo", "Số CMT", "", 100, true, true);
            UISetting.AddColumn(ref dgvList, "Department_Name", "Phòng ban", "", 150, true, true);            
            UISetting.AddColumn(ref dgvList, "doiso_sosotam", "Số sổ tạm", "", 80, true, true);
            UISetting.AddColumn(ref dgvList, "doiso_sosodoi", "Số sổ BHXH", "", 80, true, true);
            UISetting.AddColumn(ref dgvList, "doiso_loai", "Loại đổi sổ", "", 80, false, true);
            UISetting.AddColumn(ref dgvList, "doiso_ngaynhap", "Ngày nhập", "", 100, true, true);
        }
        private void LoadData()
        {
            _month = Convert.ToInt32(cboMonth.Text);
            int temptYear;
            if (Int32.TryParse(cboYear.Text, out temptYear))
                _year = temptYear;
            DataSet _ds = wcfDoiSo.HRM_Doiso_GetList(out itemCount, _month, _year, branch_ID,department_ID, currPage, pageSize);
            int n = _ds.Tables[0].Rows.Count;
            PageIndex();
            dgvList.Rows.Clear();
            for (int i = 0; i < n; i++)
            {
                dgvList.Rows.Insert(i, 1);
                dgvList.Rows[i].Cells["doiso_ID"].Value = _ds.Tables[0].Rows[i]["doiso_ID"].ToString();
                dgvList.Rows[i].Cells["doiso_branchID"].Value = _ds.Tables[0].Rows[i]["doiso_branchID"].ToString();
                dgvList.Rows[i].Cells["doiso_employeeID"].Value = _ds.Tables[0].Rows[i]["doiso_employeeID"].ToString();
                dgvList.Rows[i].Cells["Employee_FullName"].Value = _ds.Tables[0].Rows[i]["Employee_FullName"].ToString();
                dgvList.Rows[i].Cells["Employee_DateOfBirth"].Value = Convert.ToDateTime(_ds.Tables[0].Rows[i]["Employee_DateOfBirth"]).ToString("dd/MM/yyyy");
                dgvList.Rows[i].Cells["Employee_IDCardNo"].Value = _ds.Tables[0].Rows[i]["Employee_IDCardNo"].ToString();
                dgvList.Rows[i].Cells["Department_Name"].Value = _ds.Tables[0].Rows[i]["Department_Name"].ToString();
                dgvList.Rows[i].Cells["doiso_ngaynhap"].Value = Convert.ToDateTime(_ds.Tables[0].Rows[i]["doiso_ngaynhap"]).ToString("dd/MM/yyyy");
                dgvList.Rows[i].Cells["doiso_sosotam"].Value = _ds.Tables[0].Rows[i]["doiso_sosotam"].ToString();
                dgvList.Rows[i].Cells["doiso_sosodoi"].Value = _ds.Tables[0].Rows[i]["doiso_sosodoi"].ToString();
                dgvList.Rows[i].Cells["doiso_loai"].Value = _ds.Tables[0].Rows[i]["doiso_loai"].ToString();
                //Hight những trường hợp số sổ đã được đổi
                if (_ds.Tables[0].Rows[i]["doiso_sosodoi"].ToString() == _ds.Tables[0].Rows[i]["Employee_SIBookno"].ToString())
                {
                    dgvList.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
                    dgvList.Rows[i].DefaultCellStyle.SelectionBackColor = Color.Yellow;
                    dgvList.Rows[i].Cells["Check"].ReadOnly = true;
                }
            }
                           
            _loadedData = true;
        }
        private void PageIndex()
        {
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage == 0)
                lblPageIndex.Text = "0" + "/" + totalPage.ToString();
            else
                lblPageIndex.Text = (currPage + 1).ToString() + "/" + totalPage.ToString();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (!listRole.Create)
            {
                MessageBox.Show(UpdateUI.GetString("khongcoquyenthemmoi"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            frmMergeBookInfo f = new frmMergeBookInfo(0, listRole, 0);
            f.afterSave += new frmMergeBookInfo.AfterSave(LoadData);
            if (f.ShowDialog(this) == DialogResult.OK)
            {
                LoadData();
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dgvList.SelectedCells.Count > 0)
            {
                if (listRole.Update || listRole.View)
                {
                    doiso_ID = Convert.ToInt32(dgvList.Rows[dgvList.SelectedCells[0].RowIndex].Cells["doiso_ID"].Value);
                    Form f = new frmMergeBookInfo(doiso_ID, listRole, 0);
                    if (f.ShowDialog(this) == DialogResult.OK)
                    {
                        LoadData();
                    }
                }
                else
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenxem"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            dgvList.EndEdit();
            if (dgvList.SelectedCells!=null)
            {
                if (!listRole.Delete)
                {
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenxoa"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                if (MessageBox.Show(UpdateUI.GetString("bancochacchanxoa"), UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    bool complete = true;
                    foreach (DataGridViewRow row in dgvList.Rows)
                    {
                        doiso_ID = Convert.ToInt32(row.Cells["doiso_ID"].Value.ToString());
                        if (Convert.ToBoolean(row.Cells["Check"].Value))
                        {
                            if (!wcfDoiSo.HRM_Doiso_Delete(doiso_ID))
                                complete = false;
                        }
                    }

                    if (complete)
                    {
                        Program.taskbarNotifier.Show(UIParamater.TitleProject, UpdateUI.GetString("xoathanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                        LoadData();
                    }
                    else
                    {
                        MessageBox.Show(UpdateUI.GetString("xoakhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

        private void btnFisrt_Click(object sender, EventArgs e)
        {
            currPage = 0;
            LoadData();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (currPage > 0)
                currPage--;
            LoadData();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (totalPage > 0 && currPage < totalPage - 1)
                currPage++;
            LoadData();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            if (totalPage > 0)
                currPage = totalPage - 1;
            LoadData();
        }

        private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
                btnEdit_Click(null, null);
        }

        private void frmEditBookList_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    this.Dispose();
                    this.Close();
                    break;
                case Keys.F2:
                    btnNew_Click(null, null);
                    break;
                case Keys.F3:
                    btnEdit_Click(null, null);
                    break;
                case Keys.Delete:
                    btnDel_Click(null, null);
                    break;
            }
        }

        private void btnNewPopUp_Click(object sender, EventArgs e)
        {
            btnNew_Click(null, null);
        }

        private void btnEditPopUp_Click(object sender, EventArgs e)
        {
            btnEdit_Click(null, null);
        }

        private void btnDelPopUp_Click(object sender, EventArgs e)
        {
            btnDel_Click(null, null);
        }

      

        private void tvBranch_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Level == 0)
            {
                if (Program.isAdmin || Program.isViewAll)
                {
                    branch_ID = 0;
                    department_ID = 0;
                }
                else
                    branch_ID = Program.intBranchID;
                LoadData();
            }
            else if (e.Node.Level == 1)
            {
                branch_ID = Convert.ToInt32(e.Node.Tag);
                department_ID = 0;
                currPage = 0;
                LoadData();
            }
            else if (e.Node.Level >= 2)
            {
                department_ID = Convert.ToInt32(e.Node.Tag);
                branch_ID = Convert.ToInt32(e.Node.Parent.Tag);
                currPage = 0;
                LoadData();

            }
        }

        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_loadedData)
            {
                currPage = 0;
                LoadData();
            }
        }

        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_loadedData)
            {
                currPage = 0;
                LoadData();
            }
        }

        private void frmEditBookList_Activated(object sender, EventArgs e)
        {
            LoadLanguage();
            if (dgvList.Columns.Count > 0)
            {
                dgvList.Columns["FullName"].HeaderText = UpdateUI.GetString("hovaten");
                dgvList.Columns["Grant_Name"].HeaderText = UpdateUI.GetString("denghi");
                dgvList.Columns["SubGrant_Name"].HeaderText = UpdateUI.GetString("noidung");
                dgvList.Columns["EditInsBook_Amount"].HeaderText = UpdateUI.GetString("sotien");
                dgvList.Columns["EditInsBook_Date"].HeaderText = UpdateUI.GetString("ngay");
                dgvList.Columns["EditInsBook_Description"].HeaderText = UpdateUI.GetString("ghichu");
            }
        }

        private void frmEditBookList_FormClosing(object sender, FormClosingEventArgs e)
        {
            wcfBranch.Close();
            wcfDepartment.Close();
            wcfDoiSo.Close();
        }

        private void dgvList_MouseDown(object sender, MouseEventArgs e)
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                if (e.Button == MouseButtons.Right)
                {
                    mnuPopUp.Enabled = true;
                    btnNewPopUp.Enabled = true;
                    btnEditPopUp.Enabled = true;
                    btnDelPopUp.Enabled = true;
                }
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {

            if (listRole.View)
            {
                frmPreviewReport f = new frmPreviewReport("DieuChinhHS_BHXH_BHYT", new string[] { "Đề nghị điều chỉnh HS BHYT, BHXH", cboMonth.ComboBox.SelectedValue.ToString(), cboYear.ComboBox.SelectedValue.ToString() });
                f.Show(this);
            }
            else
                MessageBox.Show("Bạn không có quyền xem!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            frmTime f = new frmTime(1);
            string fileName = "DoiSoTam.xls";

            DataTable dt = new DataTable();

            if (f.ShowDialog(this) == DialogResult.OK)
            {
                //dt = _wcfPremium.Premium_GetByDate(f.FromDate, f.ToDate, Program.strBranchCode, 1, "").Tables[0];
                dt = wcfDoiSo.HRM_Doiso_Excel(f.FromDate,f.ToDate,Program.intBranchID).Tables[0];
                try
                {
                    if (dt.Rows.Count > 0)
                    {
                        ExportData2Excel(dt, Path.GetTempPath() + "\\" + fileName);
                        try
                        {
                            System.Diagnostics.Process.Start(Path.GetTempPath() + "\\" + fileName);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Không mở được File \n" + Path.GetTempPath() + "\\" + fileName, "Thông báo");
                        }
                    }
                    else
                        Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), "Không có dữ liệu!", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("File " + Path.GetTempPath() + "\\" + fileName + " đang được mở bằng một ứng dụng khác.\nHãy chọn file khác!", "Thông báo");
                }
            }
        }

        private void ExportData2Excel(DataTable dt, string _FileName)
        {
            if (dt.Columns.Contains("doiso_sosotam"))
                dt.Columns["doiso_sosotam"].Caption = "SOTAM";

            if (dt.Columns.Contains("doiso_sosodoi"))
                dt.Columns["doiso_sosodoi"].Caption = "SOBHXH";

            ReadExcelFile.exportDataToExcel(dt, _FileName);
        }

        private void ChkCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            if (ChkCheckAll.Checked)
            {
                for (int i = 0; i < dgvList.Rows.Count; i++)
                {
                    if(dgvList.Rows[i].Cells["Check"].ReadOnly == false)
                        dgvList.Rows[i].Cells["Check"].Value = true;
                }
            }
            else
            {
                for (int i = 0; i < dgvList.Rows.Count; i++)
                {
                    if (dgvList.Rows[i].Cells["Check"].ReadOnly == false)
                        dgvList.Rows[i].Cells["Check"].Value = false;
                }
            }
            GetSelectedID();
        }
        private void GetSelectedID()
        {
            dgvList.EndEdit();
            foreach (DataGridViewRow row in dgvList.Rows)
            {
                if (Convert.ToBoolean(row.Cells["Check"].Value))
                {
                    if (!_selectedID.Contains("," + row.Cells["doiso_employeeID"].Value.ToString() + ","))
                        _selectedID += row.Cells["doiso_employeeID"].Value.ToString() + ",";
                }
                else
                {
                    string sOld = "," + row.Cells["doiso_employeeID"].Value.ToString() + ",";
                    if (_selectedID.Contains(sOld))
                        _selectedID = _selectedID.Replace(sOld, ",");
                }
            }
        }

        private void btnDoiso_Click(object sender, EventArgs e)
        {
            GetSelectedID();
            if (_selectedID == ",")
            {
                MessageBox.Show("Bạn chưa chọn nhân viên cần đổi số sổ!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (listRole.View)
            {
                foreach (DataGridViewRow row in dgvList.Rows)
                {
                    if (Convert.ToBoolean(row.Cells["Check"].Value))
                    {
                        wcfEployee.Employee_UpdateSIBookNo(row.Cells["doiso_sosotam"].Value.ToString(), row.Cells["doiso_sosodoi"].Value.ToString());
                    }
                }
                LoadData();
            }
            else
                MessageBox.Show("Bạn không có quyền đổi số sổ!", UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }
}